package org.project.d.starter.network.start;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.project.d.network.coder.PacketDecoder;
import org.project.d.network.coder.PacketEncoder;
import org.project.d.network.handler.ConnectionEvent;
import org.project.d.network.handler.ConnectionHandler;
import org.project.d.network.handler.MsgDispatcherHandler;

/**
 * @author lin
 * Email 451846939@qq.com
 * @version V1.0
 * @description
 * @date 2020/3/16 11:29 下午
 */
@Slf4j
public class TcpServerStart {
    public static void main(String[] args) {
        int port = 8080;
        startServer(port);
    }

    private static void startServer(int port) {
        try {
//            SerializationManager.addSerializer((byte)3, new MyFrameSerializtion());
            ServerBootstrap b = new ServerBootstrap();
            EventLoopGroup bossGroup = new NioEventLoopGroup();
            EventLoopGroup workGroup = new NioEventLoopGroup(4);
            b.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childOption(ChannelOption.TCP_NODELAY, true)
//                    .option(ChannelOption.SO_BROADCAST, true)
                    .childHandler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel channel)
                                throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            //将 LogEventDecoder 和 LogEventHandler 添加到 ChannelPipeline 中
//                            pipeline.addLast(new IdleStateHandler(3, 0, 0, TimeUnit.SECONDS));
                            pipeline.addLast(new IdleStateHandler(0,0,3));
                            pipeline.addLast(new PacketDecoder());
                            pipeline.addLast(new PacketEncoder());
                            pipeline.addLast(new ConnectionHandler(ConnectionEvent.builder().build()));
                            pipeline.addLast(new MsgDispatcherHandler());
                        }
                    });
            b.bind(port).addListener(future -> {
                if (future.isSuccess()) {
                    log.info("tcp server start success on:{}", port);
                } else {
                    log.error("tcp server start failure on:{}", port, future.cause());
                }
            }).sync().channel().closeFuture().await();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
